<template>
  <div class="first row flex">
    <div class="total cursor" @click="setRange('value')">
      <div class="label">
        总市值
        <el-icon @click="toggleShowData"><View v-if="!showData" /><Hide v-if="showData" /></el-icon>
      </div>
      <div class="hold-total value">{{ dataLabel(totalValue.toFixed(2)) }}</div>
    </div>
    <div class="record cursor" @click="setRange('timeLong')">
      <div class="label">已记录(天)</div>
      <div class="value right">{{ days }}</div>
    </div>
  </div>
  <div class="second flex row">
    <div class="total-cost">
      <div class="label">净投入(元)</div>
      <div class="value">{{ dataLabel(totalCost.toFixed(2)) }}</div>
    </div>

    <div class="total-earnings cursor" @click="setRange('earnings')">
      <div class="label">持有收益(元)</div>
      <div class="value right">{{ dataLabel(holdEarnings) }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { HoldItem } from '@/indexDB/initHold'
import type { RangeType } from './useRange'
import { View, Hide } from '@element-plus/icons-vue'
import { computed, ref, watchEffect } from 'vue'
import { useView } from '@/hooks/useView'

const props = defineProps<{
  list: HoldItem[]
  days: string | number
  holdValue: number
}>()

const emit = defineEmits(['update:holdValue', 'range'])
const totalValue = ref(0)
const totalCost = ref(0)
const holdEarnings = computed(() => {
  return (totalValue.value - totalCost.value).toFixed(2)
})

watchEffect(() => {
  totalValue.value = 0
  totalCost.value = 0
  props.list.forEach((each) => {
    const { holdValue, holdPrice, holdNum } = each
    const holdCost = +(holdPrice * holdNum).toFixed(2)
    totalCost.value += holdCost
    totalValue.value += Number(holdValue)
  })

  emit('update:holdValue', totalValue.value)
})

const setRange = (type: RangeType) => {
  emit('range', type)
}

const { showData, dataLabel, toggleShowData } = useView()
</script>

<style lang="scss" scoped>
.row {
  margin-bottom: 20px;
  &.flex {
    display: flex;
    justify-content: space-between;
  }
  &.second {
    margin-bottom: 0;
  }
}

.label {
  margin-bottom: 10px;
  font-size: 22px;
  font-weight: 700;
}
.value {
  font-size: 22px;
  font-weight: 400;
  &.right {
    text-align: end;
  }
}
.cursor {
  cursor: pointer;
}
.total {
  .label {
    display: flex;
    align-items: center;
    .el-icon {
      margin-left: 10px;
    }
  }
}
</style>
